﻿using Forum.Infrastructure;
using Forum.Infrastructure.Util;
using Forum.Model;
using Forum.Model.Dto;
using Forum.Model.Entity;
using Forum.Model.Entity.System;
using Forum.Model.Pager;
using Forum.Model.Request;
using Forum.Repository.Extensions;
using Forum.Repository.Interface;
using Forum.Service.Interface;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using System.Net;

namespace Forum.Service.Service
{
    public class UserInfoService : IUserInfoService
    {
        private readonly IAppRepository<SYS_USER> Repository;
        private readonly IAppRepository<User> _userRep;
        private readonly IAppRepository<RefreshToken> _TokenRepository;
        private readonly IUserRepository _userRepository;
        private readonly IAppRepository<SYS_ROLE> _RoleRepository;
        private readonly JWTTokenOptions _JWTTokenOptions;
        private readonly IWebHostEnvironment _environment;

        public UserInfoService(IAppRepository<SYS_USER> appRepository, IAppRepository<User> userRep, IAppRepository<RefreshToken> TokenRepository, IUserRepository userRepository, IAppRepository<SYS_ROLE> RoleRepository, IOptionsMonitor<JWTTokenOptions> jwtTokenOptions, IWebHostEnvironment webHostEnvironment)
        {
            Repository = appRepository;
            _userRep = userRep;
            _TokenRepository = TokenRepository;
            _userRepository = userRepository;
            _RoleRepository = RoleRepository;
            _JWTTokenOptions = jwtTokenOptions.CurrentValue;
            _environment = webHostEnvironment;
        }

        /// <summary>
        /// 查询用户列表信息
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public IPagedList<SYS_USER> GetPagedList(UserQueryParameters param)
        {
            var querySet = Repository.SugarQueryable;

            // 关键词过滤
            if (!string.IsNullOrEmpty(param.Search))
            {
                querySet = querySet.Where(a => a.UserName.Contains(param.Search) || a.UserCode.Contains(param.Search));
            }
            // 是否可用
            if (!string.IsNullOrWhiteSpace(param.ISACTIVE))
            {
                querySet = querySet.Where(a => a.ISACTIVE == param.ISACTIVE);
            }
            // 排序
            querySet = querySet.OrderByDescending(a => a.UserCode);
            if (!string.IsNullOrEmpty(param.SortBy))
            {
                // 是否升序
                var ascending = !param.SortBy.StartsWith("-") ? " asc" : " desc";
                var orderByProperty = param.SortBy.Trim('-');

                querySet = querySet.OrderBy(orderByProperty + ascending);
            }
            var userList = querySet.ToPage(param.Page, param.PageSize);


            //var retuenList= userList.MapToList<SYS_USER, UserInfoResp>();
            return userList;
        }


        /// <summary>
        /// 批量新增用户
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public async Task<int> AddUsers(List<UserInfoReq> req)
        {
            var entitys = req.MapToList<UserInfoReq, SYS_USER>();
            foreach (var en in entitys)
            {
                en.UserId = Guid.NewGuid().ToString().ToUpper();

                var id = _userRepository.GetIncrementId("userinfo");
                en.UserCode = "T" + id.ToString().PadLeft(4, '0');
            }

            return await _userRepository.AddUsers(entitys);
        }

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public bool AddUser(UserInfoReq req)
        {
            CreateImage(req.Avatar, req.UserName);

            var user = req.MapTo<UserInfoReq, User>();

            user.UserId = Guid.NewGuid().ToString().ToUpper();
            user.Createdon = DateTime.Now;

            var id = _userRepository.GetIncrementId("userinfo");
            user.UserCode = "T" + id.ToString().PadLeft(4, '0');

            var resp = Repository.Insert(user);
            return resp ? true : false;
        }

        /// <summary>
        /// 将文件流转成图片存储到服务器上
        /// </summary>
        /// <param name="image"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        private string CreateImage(string image, string userName)
        {
            if (!string.IsNullOrEmpty(image))
            {
                //string filePath = Appsettings.App("FileBaseUrl");

                var filePath = Path.Combine(_environment.ContentRootPath, "Avatar");
                int startIndex = image.IndexOf(',');
                string imgBase64 = image.Substring(startIndex + 1); //获取data:image/jpeg;base64,后的正文

                int typestartIndex = image.IndexOf("/");
                int typeEndIndex = image.IndexOf(";");
                string type = image.Substring(typestartIndex + 1, typeEndIndex - typestartIndex - 1);//获取图片类型

                byte[] bt = Convert.FromBase64String(imgBase64);//获取图片base64
                string fileName = userName;//用户名做文件名
                string ImageFilePath = Path.Combine(filePath, fileName);
                if (Directory.Exists(filePath) == false)//如果不存在就创建文件夹
                {
                    Directory.CreateDirectory(filePath);
                }

                File.WriteAllBytes(ImageFilePath + "." + type, bt); //保存图片到服务器，然后获取路径  
                string url = ImageFilePath + "." + type;
                return url;//返回保存后的路径
            }
            return string.Empty;
        }

        /// <summary>
        /// 查询用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public UserInfoResp GetUser(string userId)
        {
            var userInfo = _userRep.FindEntity(a => a.UserId == userId || a.UserCode == userId);
            if (userInfo == null)
                return new UserInfoResp();

            var user = userInfo.MapTo<User, UserInfoResp>();
            user.Roles = _RoleRepository.Db.Queryable<SYS_ROLE>()
                 .InnerJoin<SYS_USER_ROLE>((a, b) => a.ID == b.ROLE_ID)
                 .WhereIF(userInfo != null && !string.IsNullOrWhiteSpace(userInfo.UserId), (a, b) => b.USER_ID == userInfo.UserId)
                 .Where((a, b) => a.ISACTIVE == "Y" && b.ISACTIVE == "Y")
                 .ToList(a => a.NAME);

            return user;
        }

        /// <summary>
        /// 更新密码
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public bool UpdatePwd(PwdReq req)
        {
            var userInfo = _userRep.FindEntity(a => a.UserId == req.userId && a.Password == req.password);
            if (userInfo != null)
            {
                userInfo.Password = req.newPassword;
                return Repository.Update(userInfo);
            }
            return false;
        }

        public string UploadAvatar(IFormFile file)
        {
            InitPostMediaDir();

            var filename = WebUtility.UrlEncode(file.FileName);
            var fileRelativePath = Path.Combine("media", "user", filename);
            var savePath = Path.Combine(_environment.WebRootPath, fileRelativePath);
            if (File.Exists(savePath))
            {
                // 上传文件重名处理
                var newFilename = $"{Path.GetFileNameWithoutExtension(filename)}-{GuidUtils.GuidTo16String()}{Path.GetExtension(filename)}";
                fileRelativePath = Path.Combine("media", "user", newFilename);
                savePath = Path.Combine(_environment.WebRootPath, fileRelativePath);
            }

            using (var fs = new FileStream(savePath, FileMode.Create))
            {
                file.CopyTo(fs);
            }

            return Path.Combine(SystemConfig.imageUrl, fileRelativePath);
        }

        private string InitPostMediaDir()
        {
            var blogMediaDir = Path.Combine(_environment.WebRootPath, "media", "user");
            if (!Directory.Exists(blogMediaDir)) Directory.CreateDirectory(blogMediaDir);

            return blogMediaDir;
        }
    }
}
